#include <iostream>
#include "Socket.hpp"
#include <memory>
#include "Epoller.hpp"
#include "TcpServer.hpp"
#include "ServerCal.hpp"

ServerCal serverCal;

extern LOG lg;

void DefaultOnMessage(std::weak_ptr<Connection> conn)
{
    if(conn.expired())
    {
        lg(ERROR,"conn is expired");
        return;
    }
    std::shared_ptr<Connection> connection = conn.lock();//将weak_ptr转换为shared_ptr
    lg(INFO,"DefaultOnMessage debug");
    //这里做接收好的数据的处理再发送出去
    if(connection->Inbuffer().empty())
    {
        lg(ERROR,"Inbuffer is empty");
        return;
    }
    lg(INFO,"Inbuffer:%s",connection->Inbuffer().c_str());
    string tmp=serverCal.Calculator(connection->Inbuffer());//这里进行处理时，缓冲区中的数据会进行删除
    connection->AppendOutbuffer(tmp);
    lg(INFO,"Parpared to send:%s",tmp.c_str());
    std::shared_ptr<TcpServer> tcpserver= connection->getServer().lock();//将weak_ptr转换为shared_ptr,设置的回调指针！
    tcpserver->Sender(connection);
}

//测试tcpserver不要使用telnet，会加入很多分隔符，不利于序列化与反序列化，所以要编写客户端
int main()
{
//    std::shared_ptr<TcpServer> server=new TcpServer(8080,nullptr);//不能这样构造
    std::shared_ptr<TcpServer> server(new TcpServer(8888,DefaultOnMessage));
    server->Init();
    server->Loop();
        
    return 0;
}